﻿/*                              
   Copyright 2011 Nils Kopal, Christopher Krüger, Simone Sauer, Dennis Nolte, Uni Duisburg-Essen

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System.IO;
using System.Net.Sockets;
using Sharebert.DownloadLibrary.Interfaces;
using System.Xml.Serialization;
using System;

namespace Sharebert.DownloadLibrary
{
    /// <summary>
    /// A DownloadClientHandler for handling download requests of a DownloadClient
    /// </summary>
    public class DownloadClientHandler : IDownloadClientHandler
    {
        private readonly TcpClient _tcpClient;
        private readonly DownloadListener _downloadListener;

        internal DownloadClientHandler(TcpClient tcpClient, DownloadListener downloadListener)
        {
            _tcpClient = tcpClient;
            _downloadListener = downloadListener;
            MessageSize = 1024*50;
        }
        #region IDownloadClientHandler Members

        public int MessageSize { get; set; }

        /// <summary>
        /// Send the file with the given filename to the remote client
        /// </summary>
        /// <param name="filename"></param>
        public void SendFile(string filename)
        {
            _downloadListener.IncreaseDownloaders();
            BinaryReader reader = null;
            try
            {
                var info = new FileInfo(filename);
                reader = new BinaryReader(new FileStream(filename, FileMode.Open));
                filename = info.Name; //remove folder information
                var clientStream = _tcpClient.GetStream();

                var totalNeededMessages = (int)Math.Ceiling((double)info.Length / MessageSize);
                for (var i = 0; i < totalNeededMessages - 1; i++)
                {
                    var payload = new byte[MessageSize];
                    var readbytes = reader.ReadBytes(MessageSize);
                    Array.Copy(readbytes, 0, payload, 0, MessageSize);
                    var message = new Message();
                    message.Header.MessageType = MessageType.FilePartMessage;
                    var filePartMessage = new FilePartMessage();
                    filePartMessage.Filesize = info.Length;
                    filePartMessage.Filename = filename;
                    filePartMessage.Bytes = payload;
                    filePartMessage.Offset = i * MessageSize;
                    filePartMessage.LastOne = false;
                    var serializer = new XmlSerializer(typeof(FilePartMessage));
                    var stream = new MemoryStream();
                    serializer.Serialize(stream, filePartMessage);
                    message.Payload = stream.ToArray();
                    Message.SendMessage(clientStream, message);
                }

                var finalpayload = new byte[info.Length - ((totalNeededMessages - 1) * MessageSize)];                
                var lastbytes = reader.ReadBytes(finalpayload.Length);
                Array.Copy(lastbytes, 0, finalpayload, 0, finalpayload.Length);
                var finalmessage = new Message();
                finalmessage.Header.MessageType = MessageType.FilePartMessage;
                var finalfilePartMessage = new FilePartMessage();
                finalfilePartMessage.Filesize = info.Length;
                finalfilePartMessage.Filename = filename;
                finalfilePartMessage.Bytes = finalpayload;
                finalfilePartMessage.Offset = (totalNeededMessages - 1) * MessageSize;
                finalfilePartMessage.LastOne = true;
                var finalserializer = new XmlSerializer(typeof(FilePartMessage));
                var finalstream = new MemoryStream();
                finalserializer.Serialize(finalstream, finalfilePartMessage);
                finalmessage.Payload = finalstream.ToArray();
                Message.SendMessage(clientStream, finalmessage);
                _tcpClient.Close();
            }
            finally
            {
                _downloadListener.DecreaseDownloaders();
                _downloadListener.Clients.Remove(_tcpClient);
                if (reader != null)
                {
                    try
                    {
                        reader.Close();
                    }
                    catch(Exception)
                    {
                        //wtf?
                    }
                }
            }
        }

        /// <summary>
        /// Send to the DownloadClient that the file was not found
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="filesize"></param>
        public void FileNotFound(string filename, long filesize)
        {
            try
            {
                var clientStream = _tcpClient.GetStream();
                var message = new Message();
                message.Header.MessageType = MessageType.FileNotFoundMessage;
                var fileNotFoundMessage = new FileNotFoundMessage();
                fileNotFoundMessage.Filename = filename;
                fileNotFoundMessage.Filesize = filesize;
                var serializer = new XmlSerializer(typeof (FileNotFoundMessage));
                var stream = new MemoryStream();
                serializer.Serialize(stream, fileNotFoundMessage);
                message.Payload = stream.ToArray();
                Message.SendMessage(clientStream, message);
                _tcpClient.Close();
            }
            finally
            {
                _downloadListener.Clients.Remove(_tcpClient);
            }
        }

        #endregion
    }
}
